package com.dqhl.community.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.arrownock.exception.ArrownockException;
import com.arrownock.social.AnSocialMethod;
import com.arrownock.social.IAnSocialCallback;
import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.User;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.GetVersion;
import com.dqhl.community.util.JPushUtil;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.UserSaveUtil;
import com.mob.tools.utils.UIHandler;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WXTextObject;

/**
 * Created by guanluocang on 2016/8/29.
 * 登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, Handler.Callback, PlatformActionListener {

    private boolean quit = false; //设置退出标识
    private Button btnLogin; //  登录
    private TextView tvRegister; // 注册
    private TextView tvForgetPwd; //忘记密码
    private ImageView ivLoginWeixin; // 微信登录
    private ImageView ivLoginQQ; //qq登录
    private EditText etTelephone;
    private EditText etPassword;
    private String strTelephone;
    private String strPassword;
    WXTextObject wxTextObject = null;
    //  微信登录参数
    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    // 微信登录的ID
    private static final String APP_ID = "wx99f39979a99bfe44";
    private static final String APP_SCCRET = "69b3397f9cfd5bb4daaf8202397d74e5";
    // 登录回复结果
    private static String res_Unionid = null;
    private Context mContext;
    private static String Wx_login = null;
    private TextView tv_version;// 版本号
    private String version;
    private ImageView iv_close;
    private String platformName = "";
    private String userId = "";
    private String userName = "";
    private String photoPath = "";
    private HashMap<String, Object> res_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this.getApplicationContext();
        initView();
        GetVersion.getVersion(mContext, tv_version);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvRegister = (TextView) findViewById(R.id.tv_register);
        tvForgetPwd = (TextView) findViewById(R.id.tv_forget_pwd);
        ivLoginWeixin = (ImageView) findViewById(R.id.iv_login_weixin);
        ivLoginQQ = (ImageView) findViewById(R.id.iv_login_qq);
        etTelephone = (EditText) findViewById(R.id.et_telephone);
        etPassword = (EditText) findViewById(R.id.et_pwd);
        tv_version = (TextView) findViewById(R.id.text_version);
        iv_close = (ImageView) findViewById(R.id.iv_close);

        btnLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvForgetPwd.setOnClickListener(this);
        ivLoginWeixin.setOnClickListener(this);
        ivLoginQQ.setOnClickListener(this);
        iv_close.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
            case R.id.btn_login: //跳转到MainActivity
                doLogin();
                break;
            case R.id.tv_register: //跳转到注册Activity
                overlay(RegisterActivity.class);
                break;
            case R.id.tv_forget_pwd: //忘记密码
                overlay(ForgetPwdActivity.class);
                break;
            case R.id.iv_login_weixin: //微信登录
                doLoginWeixin();
                break;
            case R.id.iv_login_qq: //QQ登录
                doLoginQQ();
                break;
        }
    }

    private void doLoginWeixin() {
        //  判断是否安装微信
        isWeixinAvilible(mContext);
    }

    private void doLoginQQ() {
        isQQClientAvailable(mContext);
    }


    /**
     * 验证登录
     */
    private void doLogin() {
        strTelephone = etTelephone.getText().toString().trim();
        strPassword = etPassword.getText().toString().trim();
        if (strTelephone.equals("") || strTelephone.length() <= 0) {
            toast(R.string.toast_telephone_null);
        } else if (strPassword.equals("") || strPassword.length() <= 0) {
            toast(R.string.toast_password_null);
        } else {
            showCustomLoadBar("登录中…");
            // 请求接口，验证用户信息
            RequestParams params = new RequestParams(Config.Api.login);
            params.addBodyParameter("mobile_number", strTelephone);
            params.addBodyParameter("password", strPassword);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getInfo(result, "errMsg");
                    String data = JsonUtils.getInfo(result, "data");
                    Dlog.e("GG登录返回" + data);

                    if (errCode == 0) {
                        User user = JSON.parseObject(data, User.class);
//                        UserSaveUtil.saveUser(LoginActivity.this, user);

                        UserSaveUtil.saveUser(mContext, user);

                        String userid = user.getUserid();
                        String authentication = user.getAuthentication();
                        String community_id = user.getCommunity_id();
                        String building_id = user.getBuilding_id();
                        String unit_id = user.getUnit_id();
                        String residence_id = user.getResidence_id();
                        String address = community_id + building_id + unit_id + residence_id;
                        String sex = user.getSex();
                        String nickname = user.getNickname();
                        String head_img = user.getHead();
                        String name = user.getName();
                        String wxstate = user.getWxstate();
                        String qqstate = user.getQqstate();
                        String integral = user.getIntegral();
                        // 将user信息放到application中
                        app.setUserId(userid);
                        app.setUsername(strTelephone);
                        app.setPwd(strPassword);
                        app.setAuthentication(authentication);

                        // 将userid放到SharedPreferences中
                        SharedPreferences.Editor editor = spUserInfo.edit();
                        editor.putString(Constant.USER_PHONE, strTelephone);
                        editor.putString(Constant.ANIM_PHONE, userid);
                        editor.putString(Constant.ANIM_PWD, userid);
                        editor.putString(Constant.USERID, userid);
                        editor.putString(Constant.NICKNAME, nickname);
                        editor.putString(Constant.AUTHENTICATION, authentication);
                        editor.putString(Constant.COMMUNITY_ID, community_id);
                        editor.putString(Constant.ADDRESS, address);
                        editor.putString(Constant.SEX, sex);
                        editor.putString(Constant.PHOTO_PATH, head_img);
                        editor.putString(Constant.NAME, name);
                        editor.putString(Constant.WXSTATE, wxstate);
                        editor.putString(Constant.QQSTATE, qqstate);
                        editor.putString(Constant.COUPONS_COUPON,integral);
                        editor.apply();
                        Dlog.e("userid:" + userid);
                        JPushAlias(userid);
                        sendLoginSuccessBroadCast();
                        finish();
                    } else {
                        toast(errMsg);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    toast(R.string.error_net_connection);
                    Dlog.e("网络连接失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });

        }
    }

    /**
     * 发送一个登录成功的广播
     */
    private void sendLoginSuccessBroadCast() {
        Intent intent = new Intent(Constant.ACTION_LOGIN_SUCCESS);
        intent.putExtra(Constant.USER_PHONE, strTelephone);
        sendBroadcast(intent);
    }

    // 判断手机是否安装微信
    private boolean isWeixinAvilible(Context mContext) {
        final PackageManager packageManager = mContext.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    WXEntry(1);
                    return true;
                }
            }
        }
        //  没有安装微信的
        toast("您的手机没有安装微信");
        return false;
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    WXEntry(2);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 调用微信授权登录
     */
    private void WXEntry(int flag) {
        if (flag == 1) {
            Platform plat_WX = ShareSDK.getPlatform(mContext, Wechat.NAME);
            plat_WX.removeAccount(true);
            authorize(plat_WX, 1);
        } else if (flag == 2) {
            Platform plat_QQ = ShareSDK.getPlatform(mContext, QQ.NAME);
            plat_QQ.SSOSetting(false);//设置false表示使用SSO授权方式
            plat_QQ.removeAccount(true);
            authorize(plat_QQ, 2);
        }

    }

    public void authorize(Platform plat, int type) {
        Dlog.e("GG进入授权登录authorize");
        //判断指定平台是否已经完成授权
        if (plat.isValid()) {
            Dlog.e("GG authorize  " + plat.getDb());
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                login(plat.getName(), userId, null);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        Dlog.e(userId + "GG进入授权登录login" + userInfo);
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(Platform arg0, int action) {
        Dlog.e("GG进入登录onCancel");
        // TODO Auto-generated method stub
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
//        Dlog.e("GG进入登录onComplete，登录方式：" + platform.getName());
        // TODO Auto-generated method stub
        Dlog.e(action + " GG 返回" + res);
        res_result = res;
        if (action == Platform.ACTION_USER_INFOR) {
//            Wx_login = res.get("unionid").toString();
            PlatformDb platDB = platform.getDb(); //获取平台数据DB
            //通过DB获取各种数据
            String token = platDB.getToken();
            String userGender = platDB.getUserGender();
            String userIcon = platDB.getUserIcon();
            userId = platDB.getUserId();
            userName = platDB.getUserName();
            Dlog.e("token:" + token + ";userGender:" + userGender + ";userIcon:" + userIcon
                    + ";userId:" + userId + ";userName:" + userName);
            photoPath = saveUserIcon(userIcon);
            Dlog.e("photoPath" + photoPath);
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
            login(platform.getName(), platform.getDb().getUserId(), res);

        }
        platformName = platform.getName();

    }

    /**
     * 保存头像到本地
     *
     * @param userIcon
     * @return
     */
    private String saveUserIcon(String userIcon) {
        Dlog.e("saveUserIcon_userIcon:" + userIcon);
        String sdState = Environment.getExternalStorageState();
        Dlog.e("sdState" + sdState);
        if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
            Dlog.e("sd card unmount");
        }
        String name = UUID.randomUUID().toString() + ".jpg";
        Dlog.e("name" + name);
        File file = new File(Constant.photoPath);
        file.mkdirs();
        FileOutputStream fout = null;
        String photoPath = Constant.photoPath + name;
        Dlog.e("photoPath" + photoPath);
        try {
            byte[] bytes = getImage(userIcon);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            fout = new FileOutputStream(photoPath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
        } catch (Exception e) {
            Log.d("Login", e.toString());
            e.printStackTrace();
        } finally {
            try {
                fout.flush();
                fout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Dlog.e("savePhoto:" + photoPath);
        return photoPath;
    }

    public byte[] getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(inStream);
        }
        return null;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    @Override
    public void onError(Platform arg0, int arg1, Throwable t) {
        Dlog.e(arg1 + "GG进入登录onErr" + t);
        // TODO Auto-generated method stub
        if (arg1 == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
        }
        t.printStackTrace();
    }

    protected void onDestroy() {
        ShareSDK.stopSDK(this);
        super.onDestroy();
    }


    @Override
    public boolean handleMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
            case MSG_USERID_FOUND: {
            }
            break;
            case MSG_LOGIN: {
                Toast.makeText(this, "授权登陆成功", Toast.LENGTH_SHORT).show();
                if ("QQ".equals(platformName)) {
                    // QQ登录
                    Dlog.e("qq登录传递的参数：" + userName + ";" + userId + ";" + photoPath);
                    Http_QQDenglu(userName, userId, photoPath);
                } else if ("Wechat".equals(platformName)) {
                    //  微信登录
                    String unionid = res_result.get("unionid").toString();
                    Dlog.e("GGGG进入登录onComplete,unionid: " + unionid);
                    Http_WXDenglu(userName, unionid, userId, photoPath);
                }
            }
            break;
            case MSG_AUTH_CANCEL: {
                Toast.makeText(this, "授权登陆取消", Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_ERROR: {
                Toast.makeText(this, "授权登陆错误", Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_COMPLETE: {
//			Toast.makeText(this, "授权登录完成", Toast.LENGTH_SHORT).show();
            }
            break;
        }

        return false;
    }
    //  HashMap 转换成 JSON

    public static String hashMapToJson(HashMap map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry e = (Map.Entry) it.next();
            string += "\"" + e.getKey() + "\":";
            string += "\"" + e.getValue() + "\",";
        }

        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }

    /**
     * qq第三方登录
     *
     * @param nickname
     * @param qqid
     * @param photoPath
     */
    private void Http_QQDenglu(String nickname, final String qqid, String photoPath) {
        RequestParams params = new RequestParams(Config.Api.qqLogin);
        params.addBodyParameter("nickname", nickname);
        params.addBodyParameter("qqid", qqid);
        File head = new File(photoPath);
        if (head.isFile()) {
            Dlog.e("上传QQ头像地址：" + head);
            params.addBodyParameter("head", head);
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");

                if (errCode == 0) {
                    //已经绑定了手机号，直接登录
                    saveUserInfo2sp(data);
                    sendLoginSuccessBroadCast();
                    finish();
                } else if (errCode == 1) {
                    String id = JsonUtils.getInfo(data, "id");
                    Bundle bundle = new Bundle();
                    bundle.putString("id", id);
                    //第三方注册成功，但未绑定手机号，跳到绑定手机号页面
                    forward(BindingPhoneActivity.class, bundle);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 微信登录请求接口
     *
     * @param nickname
     * @param unionid
     * @param openid
     * @param photoPath
     */
    public void Http_WXDenglu(String nickname, String unionid, final String openid, String photoPath) {
        RequestParams params = new RequestParams(Config.Api.wxLogin);
        params.addBodyParameter("nickname", nickname);
        params.addBodyParameter("openid", openid);
        params.addBodyParameter("unionid", unionid);
        File head = new File(photoPath);
        if (head.isFile()) {
            Dlog.e("上传微信头像：" + head);
            params.addBodyParameter("head", head);
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("result:" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    //已经绑定了手机号，直接登录
                    saveUserInfo2sp(data);

                    sendLoginSuccessBroadCast();
                    finish();
                } else if (errCode == 1) {
                    String id = JsonUtils.getInfo(data, "id");
                    Bundle bundle = new Bundle();
                    bundle.putString("id", id);
                    //第三方注册成功，但未绑定手机号，跳到绑定手机号页面
                    forward(BindingPhoneActivity.class, bundle);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 保存用户信息到SharedPreferences里
     *
     * @param data
     */
    private void saveUserInfo2sp(String data) {
        User user = JSON.parseObject(data, User.class);
        UserSaveUtil.saveUser(LoginActivity.this, user);

        String userid = user.getUserid();
        String authentication = user.getAuthentication();
        String community_id = user.getCommunity_id();
        String building_id = user.getBuilding_id();
        String unit_id = user.getUnit_id();
        String residence_id = user.getResidence_id();
        String address = community_id + building_id + unit_id + residence_id;
        String sex = user.getSex();
        String nickname = user.getNickname();
        String head_img = user.getHead();
        String name = user.getName();
        String phone = user.getPhone();
        String wxstate = user.getWxstate();
        String qqstate = user.getQqstate();
        // 将user信息放到application中
        app.setUserId(userid);
//                    app.setUsername(strTelephone);
//                    app.setPwd(strPassword);
        app.setAuthentication(authentication);

        // 将userid放到SharedPreferences中
        SharedPreferences.Editor editor = spUserInfo.edit();
        editor.putString(Constant.USER_PHONE, phone);
//                    editor.putString(Constant.USER_PWD, strPassword);
        editor.putString(Constant.USERID, userid);
        editor.putString(Constant.NICKNAME, nickname);
        editor.putString(Constant.AUTHENTICATION, authentication);
        editor.putString(Constant.COMMUNITY_ID, community_id);
        editor.putString(Constant.ADDRESS, address);
        editor.putString(Constant.SEX, sex);
        editor.putString(Constant.PHOTO_PATH, head_img);
        editor.putString(Constant.NAME, name);
        editor.putString(Constant.WXSTATE, wxstate);
        editor.putString(Constant.QQSTATE, qqstate);
        editor.apply();
        Dlog.e("userid:" + userid);
        //TODO userId注册箭扣科技,用户名，密码相同
        registerAnIM(userid);
    }

    /**
     * 注册箭扣科技
     *
     * @param userid
     */
    private void registerAnIM(final String userid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", userid);
        params.put("password", userid);
        params.put("password_confirmation", userid);
        params.put("enable_im", true);
        try {
            social.sendRequest(Constant.REGISTER_ANIM, AnSocialMethod.POST, params,
                    new IAnSocialCallback() {
                        @Override
                        public void onFailure(JSONObject response) {
                            try {
                                String string = response.getJSONObject("meta").getString("message");
                                Log.d("onFailure", string);
                                if ("Already existing username".equals(string)) {
                                    // 将userid放到SharedPreferences中
                                    SharedPreferences.Editor editor = spUserInfo.edit();
                                    editor.putString(Constant.ANIM_PHONE, userid);
                                    editor.putString(Constant.ANIM_PWD, userid);
                                    editor.apply();
                                }
                            } catch (Exception e1) {
                                Log.d("onFailure", e1.toString());
                            }
                        }

                        @Override
                        public void onSuccess(JSONObject response) {
                            try {
                                // 将userid放到SharedPreferences中
                                SharedPreferences.Editor editor = spUserInfo.edit();
                                editor.putString(Constant.ANIM_PHONE, userid);
                                editor.putString(Constant.ANIM_PWD, userid);
                                editor.apply();
                                Log.d("onSuccess", response.getJSONObject("response").getJSONObject("user").getString("username"));
                            } catch (Exception e1) {
                                Log.d("onSuccess", e1.toString());
                            }
                        }
                    });
        } catch (ArrownockException e) {
            e.printStackTrace();
        }
    }


    //极光推送设置别名
    public void JPushAlias(String userid) {
        if (TextUtils.isEmpty(userid)) {
            toast(R.string.error_alias_empty);
            return;
        }
        if (!JPushUtil.isValidTagAndAlias(userid)) {
            toast(R.string.error_tag_gs_empty);
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userid));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }
            Dlog.e(logs);
//            JPushUtil.showToast(logs, getApplicationContext());
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
            }
        }
    };
}
